import React, { useState, useEffect, useRef } from 'react';
import { Button, Input, UserIcon, PasswordIcon, Checkbox } from '@repo/ui';
import styles from './Login.module.css';

export interface LoginProps {
  onLogin?: (credentials: { username: string; password: string; rememberMe?: boolean }) => void;
  onForgotPassword?: () => void;
  onSignUp?: () => void;
  onClose?: () => void;
  loading?: boolean;
  error?: string;
  className?: string;
}

export const Login: React.FC<LoginProps> = ({
  onLogin,
  onForgotPassword,
  onSignUp,
  onClose,
  loading = false,
  error,
  className
}) => {
  const [username, setUsername] = useState('');
  const [password, setPassword] = useState('');
  const [usernameError, setUsernameError] = useState('');
  const [passwordError, setPasswordError] = useState('');
  const [rememberMe, setRememberMe] = useState(false);
  const usernameRef = useRef<any>(null);
  const passwordRef = useRef<any>(null);

  // 键盘快捷键支持
  useEffect(() => {
    const handleKeyDown = (e: KeyboardEvent) => {
      if (e.key === 'Escape' && onClose) {
        onClose();
      }
    };

    document.addEventListener('keydown', handleKeyDown);
    return () => document.removeEventListener('keydown', handleKeyDown);
  }, [onClose]);

  // 自动聚焦到用户名输入框
  useEffect(() => {
    if (usernameRef.current) {
      usernameRef.current.focus();
    }
  }, []);

  const handleSubmit = (e: React.FormEvent) => {
    e.preventDefault();
    
    setUsernameError('');
    setPasswordError('');

    let hasError = false;

    if (!username.trim()) {
      setUsernameError('请输入用户名');
      hasError = true;
      usernameRef.current?.focus();
    } else if (username.length < 2) {
      setUsernameError('用户名长度至少2位');
      hasError = true;
      usernameRef.current?.focus();
    }

    if (!password) {
      setPasswordError('请输入密码');
      hasError = true;
      if (!hasError) passwordRef.current?.focus();
    } else if (password.length < 6) {
      setPasswordError('密码长度至少6位');
      hasError = true;
      if (!hasError) passwordRef.current?.focus();
    }

    if (!hasError) {
      onLogin?.({ username: username.trim(), password, rememberMe });
    }
  };

  const handleUsernameKeyDown = (e: React.KeyboardEvent) => {
    if (e.key === 'Enter' && username && !password) {
      passwordRef.current?.focus();
    }
  };

  const handlePasswordKeyDown = (e: React.KeyboardEvent) => {
    if (e.key === 'Enter' && username && password) {
      handleSubmit(e as any);
    }
  };

  const renderContent = () => (
    <>
      <div className={styles.loginHeader}>
        <h1 className={styles.loginTitle}>登录</h1>
        <p className={styles.loginSubtitle}>欢迎回来，请输入您的账户信息</p>
      </div>

      <form onSubmit={handleSubmit} className={styles.loginForm}>
        {error && (
          <div className={styles.errorMessage}>
            {error}
          </div>
        )}

        <div className={styles.formGroup}>
          <Input
            ref={usernameRef}
            type="text"
            label="用户名"
            placeholder="请输入用户名"
            value={username}
            onChange={(e) => setUsername(e.target.value)}
            onKeyDown={handleUsernameKeyDown}
            error={usernameError}
            required
            disabled={loading}
            autoComplete="username"
            prefixIcon={<UserIcon size={16} />}
          />
        </div>

        <div className={styles.formGroup}>
          <Input
            ref={passwordRef}
            type="password"
            label="密码"
            placeholder="请输入密码"
            value={password}
            onChange={(e) => setPassword(e.target.value)}
            onKeyDown={handlePasswordKeyDown}
            error={passwordError}
            required
            disabled={loading}
            autoComplete="current-password"
            prefixIcon={<PasswordIcon size={16} />}
          />
        </div>

        <div className={styles.loginOptions}>
          <Checkbox
            checked={rememberMe}
            onChange={setRememberMe}
            disabled={loading}
            label="记住我"
            size="md"
            variant="default"
          />
          
          {onForgotPassword && (
            <button
              type="button"
              className={styles.forgotPassword}
              onClick={onForgotPassword}
            >
              忘记密码？
            </button>
          )}
        </div>

        <Button
          type="submit"
          variant="default"
          size="lg"
          disabled={loading}
          className={styles.loginButton}
        >
          {loading ? '登录中...' : '登录'}
        </Button>
      </form>

      {onSignUp && (
        <div className={styles.signupPrompt}>
          <span>还没有账户？</span>
          <button
            type="button"
            className={styles.signupLink}
            onClick={onSignUp}
          >
            立即注册
          </button>
        </div>
      )}
    </>
  );

  return (
    <div className={`${styles.loginContainer} ${className || ''}`}>
      <div className={styles.loginCard}>
        {renderContent()}
      </div>
    </div>
  );
};

export default Login;